<?php

namespace App\Http\Controllers\dashboard;

use App\Http\Controllers\api\BaseController;
use App\Models\DashAdmin;
use App\Models\User;
use Symfony\Component\HttpFoundation\Response as HttpResponse;

class AuthController extends BaseController
{
    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request(['username', 'password']);
        $credentials['uuid'] = request()->header('uuid');

        if (empty($credentials)) {
            return $this->error('账号密码为空！');
        }
        if (!$token = auth('dash')->attempt($credentials)) {
            return $this->error('账户信息不正确', [], HttpResponse::HTTP_UNAUTHORIZED);
        }

        return $this->respondWithToken($token);
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function userinfo()
    {
        /** @var User $user */
        $user = auth('dash')->user();
        $userinfo = $this->getUserInfo($user);

        return $this->success($userinfo->toArray());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return $this->success('成功退出');
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        $user = auth('dash')->setToken($token)->user();
        return $this->success([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('dash')->factory()->getTTL() * 60,
            'user' => $this->getUserInfo($user),
        ]);
    }

    private function getUserInfo(DashAdmin $user)
    {
        return $user;
    }
}
